import React, { useEffect, useState } from "react";
import { Checkbox, Form, Input } from "antd";
import { QuestionParagraphPropsType } from "./interface";

const PropComponent: React.FC<QuestionParagraphPropsType> = (
  props: QuestionParagraphPropsType
) => {
  const { text, isCenter, onChange, disabled } = props;
  const [form] = Form.useForm();
  const [inputValue, setInputValue] = useState("");

  useEffect(() => {
    form.setFieldsValue({ text, isCenter });
  }, [text, isCenter]);

  function handleValueChange() {
    if (onChange) onChange(form.getFieldsValue());
  }

  function handleBlur() {
    const currentValue = form.getFieldValue("text");

    if (currentValue !== "") return;
    form.setFieldValue("text", inputValue);
    if (onChange) onChange(form.getFieldsValue());
    form.resetFields();
  }

  return (
    <Form
      layout="vertical"
      initialValues={{ text, isCenter }}
      form={form}
      onValuesChange={handleValueChange}
      disabled={disabled}
    >
      <Form.Item
        label="内容"
        name="text"
        rules={[{ required: true, message: "请输入内容" }]}
      >
        <Input.TextArea
          onFocus={(e) => setInputValue(e.target.value)}
          onBlur={handleBlur}
          autoSize={{ minRows: 5, maxRows: 8 }}
          allowClear
        />
      </Form.Item>
      <Form.Item name="isCenter" valuePropName="checked">
        <Checkbox>居中显示</Checkbox>
      </Form.Item>
    </Form>
  );
};

export default PropComponent;
